package com.yonyou.pmclouds.safetyrectification.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.DateUtils;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.reason.entity.ProblemReasonVO;
import com.yonyou.pmclouds.reason.rmiitf.ProblemReasonQuery;
import com.yonyou.pmclouds.safetyrectification.assignrecord.entity.AssignRecordVO;
import com.yonyou.pmclouds.safetyrectification.assignrecord.service.IAssignRecordQuery;
import com.yonyou.pmclouds.safetyrectification.entity.SafetyRectificationVO;
import com.yonyou.pmclouds.safetyrectification.mapper.SafetyRectificationMapper;
import com.yonyou.pmclouds.safetyrectification.rectificationrecord.entity.RectificationRecordVO;
import com.yonyou.pmclouds.safetyrectification.rectificationrecord.service.IRectiRecordQuery;
import com.yonyou.pmclouds.safetyrectification.relationuser.entity.RelationUserVO;
import com.yonyou.pmclouds.safetyrectification.relationuser.service.IRelationUserQuery;
import com.yonyou.pmclouds.safetyrectification.service.ISafetyRectificationQuery;
import com.yonyou.pmclouds.safetyrectification.util.SafetyRectifyUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 安全整改查询接口实现类
 *
 * @author th
 * @date 2019/10/24 13:53
 */
@Service(interfaceClass = ISafetyRectificationQuery.class, version = ApplicationConsts.APPLICATION_VERSION)
public class SafetyRectificationQueryImpl implements ISafetyRectificationQuery , IPageQuerySerivce<SafetyRectificationVO> {
    @Autowired
    private SafetyRectificationMapper mapper;
    @Autowired
    private IRectiRecordQuery rectiRecordQuery;
    @Autowired
    private IAssignRecordQuery assignRecordQuery;
    @Autowired
    private IRelationUserQuery relationUserQuery;
    @Autowired
    private PictureRemoteService pictureRemoteService;
    @Autowired
    private ProblemReasonQuery problemReasonQuery;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired
    private OrganizationQuery organizationQuery;

    @Override
    public SafetyRectificationVO getById(String id) throws BusinessException {
        SafetyRectificationVO resultVO = mapper.getById(id);
        if (resultVO == null)
            return new SafetyRectificationVO();

        // 填充整改记录
        List<RectificationRecordVO> rectiRecordList = rectiRecordQuery.getByPkBill(id);
        resultVO.setRectificationRecordList(rectiRecordList);

        // 填充交办记录
        List<AssignRecordVO> assignRecordList = assignRecordQuery.getByPkBill(id);
        resultVO.setAssignRecordList(assignRecordList);

        // 填充抄送人
        List<RelationUserVO> relationUserList = relationUserQuery.getByPkBill(id);
        resultVO.setRelationUserList(relationUserList);

        // 查询图片
        String[] pictures = pictureRemoteService.queryPicNamesByPkEntity(id);
        resultVO.setPictures(pictures);
        // 处理参照字段
        setRefFields(resultVO);

        return resultVO;
    }

    @Override
    public List<SafetyRectificationVO> getByProject(String pkProject, Integer billStatus) throws BusinessException {
        List<SafetyRectificationVO> safetyRectificationList = mapper.getByProject(pkProject, billStatus == null ?
                null : billStatus.byteValue());
        if (CollectionUtils.isEmpty(safetyRectificationList))
            return new ArrayList<>();

        // 单据主键集合
        Set<String> pkBillSet = new HashSet<>();
        Set<String> pkReasonSet = new HashSet<>();
        for (SafetyRectificationVO vo : safetyRectificationList) {
            pkBillSet.add(vo.getPkSafetyRectification());
            if (StringUtils.isNotEmpty(vo.getPkProblemReason()))
                pkReasonSet.add(vo.getPkProblemReason());
        }

        // 查询照片
        Map<String, List<String>> pictureMap = pictureRemoteService.queryPicsByPkEntitys(pkBillSet.toArray(new String[0]));
        // 查询问题原因
        Map<String, String> reasonMap = problemReasonQuery.queryNameByIds(pkReasonSet.toArray(new String[0]));

        String pkBill;
        List<String> pictures;
        for (SafetyRectificationVO rectifyVO : safetyRectificationList) {
            pkBill = rectifyVO.getPkSafetyRectification();
            // 设置照片
            if (pictureMap != null) {
                pictures = pictureMap.get(pkBill);
                if (CollectionUtils.isNotEmpty(pictures))
                    rectifyVO.setPictures(pictures.toArray(new String[0]));
            }

            //  设置问题原因名称
            if (reasonMap != null)
                rectifyVO.setProblemReasonName(reasonMap.get(rectifyVO.getPkProblemReason()));

            // 判断是否超期
            rectifyVO.setOverTime(SafetyRectifyUtil.checkOverTime(rectifyVO));
        }

        return safetyRectificationList;
    }

    @Override
    public PageObject<Object> queryByCondition(String[] pkProjects, String[] creators, String startDate, String endDate,
                                               int[] billStatus, int pageStart, int pageSize) throws BusinessException {
        int count = mapper.countByCondition(pkProjects, creators, startDate, endDate, billStatus);
        SafetyRectificationVO[] vos = mapper.queryByCondition(pkProjects, creators, startDate, endDate, billStatus, pageStart, pageSize);
        // 翻译参照
        translateRefFields(vos);

        return new PageObject<Object>(vos, count, pageStart);
    }

    /**
     * 翻译参照
     *
     * @param vos
     */
    private void translateRefFields(SafetyRectificationVO[] vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos))
            return;

        Set<String> projectSet = new HashSet<>();
        Set<String> reasonSet = new HashSet<>();
        Set<String> pkSafetySet = new HashSet<>();
        for (SafetyRectificationVO vo : vos) {
            projectSet.add(vo.getPkProject());
            reasonSet.add(vo.getPkProblemReason());
            pkSafetySet.add(vo.getPkSafetyRectification());
        }

        // 查询项目、问题原因和图片
        Map<String, String> projectMap = projectSimpleQuery.queryProjectNameByIds(projectSet.toArray(new String[0]));
        Map<String, String> reasonMap = problemReasonQuery.queryNameByIds(reasonSet.toArray(new String[0]));
        Map<String, List<String>> pictureMap = pictureRemoteService.queryPicsByPkEntitys(pkSafetySet.toArray(new String[0]));
        List<String> pictures;
        for (SafetyRectificationVO vo : vos) {
            vo.setProjectName(projectMap.get(vo.getPkProject()));
            vo.setProblemReasonName(reasonMap.get(vo.getPkProblemReason()));
            pictures = pictureMap.get(vo.getPkSafetyRectification());
            vo.setPicNum(pictures == null ? 0 : pictures.size());
            vo.setOverTime(SafetyRectifyUtil.checkOverTime(vo));
            vo.setStrBillStatus(SafetyRectifyUtil.transBillStatus(vo));
            vo.setStrSeverityLevel(SafetyRectifyUtil.transSeverityLevel(vo));
        }
    }

    /**
     * 处理参照字段
     *
     * @param resultVO
     */
    private void setRefFields(SafetyRectificationVO resultVO) throws BusinessException {
        // 问题原因
        ProblemReasonVO reasonVO = problemReasonQuery.getById(resultVO.getPkProblemReason());
        if (reasonVO != null)
            resultVO.setProblemReasonName(reasonVO.getSname());

        // 项目
        ProjectVO projectVO = projectSimpleQuery.queryProject(resultVO.getPkProject());
        if (projectVO != null) {
            resultVO.setProjectCode(projectVO.getScode());
            resultVO.setProjectName(projectVO.getSname());
            String pkOrg = projectVO.getPkOrg();
            if (StringUtils.isNotEmpty(pkOrg)) {
                OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), pkOrg);
                resultVO.setOrgName(organizationVO == null ? null : organizationVO.getSname());
            }
        }
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = mapper.countByCondition( new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public SafetyRectificationVO[] queryByProject(QueryListParam param) throws BusinessException {

        SafetyRectificationVO[] vos = mapper.queryByCondition(new String[]{param.getPkProject()}, null,  param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());

        if (ArrayUtils.isEmpty(vos))
            return new SafetyRectificationVO[0];

        // 单据主键集合
        Set<String> pkBillSet = new HashSet<>();
        Set<String> pkReasonSet = new HashSet<>();
        for (SafetyRectificationVO vo : vos) {
            pkBillSet.add(vo.getPkSafetyRectification());
            if (StringUtils.isNotEmpty(vo.getPkProblemReason()))
                pkReasonSet.add(vo.getPkProblemReason());
        }

        // 查询照片
        Map<String, List<String>> pictureMap = pictureRemoteService.queryPicsByPkEntitys(pkBillSet.toArray(new String[0]));
        // 查询问题原因
        Map<String, String> reasonMap = problemReasonQuery.queryNameByIds(pkReasonSet.toArray(new String[0]));

        String pkBill;
        List<String> pictures;
        for (SafetyRectificationVO rectifyVO : vos) {
            pkBill = rectifyVO.getPkSafetyRectification();
            // 设置照片
            if (pictureMap != null) {
                pictures = pictureMap.get(pkBill);
                if (CollectionUtils.isNotEmpty(pictures))
                    rectifyVO.setPictures(pictures.toArray(new String[0]));
            }

            //  设置问题原因名称
            if (reasonMap != null)
                rectifyVO.setProblemReasonName(reasonMap.get(rectifyVO.getPkProblemReason()));

            // 判断是否超期
            rectifyVO.setOverTime(SafetyRectifyUtil.checkOverTime(rectifyVO));
        }

        return vos;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.SAFETY_RECTIFICATION_BILLTYPE;
    }
}
